<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Gosu_authenticate {
    private $client_id 	   = 'cack.Rbvyoow386a86jbCCaLLHo35i3rsFR';
    private $client_secret = 'ZTvbyGZ2E55gdiPFSSZMdaY5cVhVxvCL9kUpDoT35uexPjWzFXN7BvFmkuKc';
    private $url_service   = 'https://id.gosu.vn'; 
    private $redirect_uri  = 'http://beta.gosu.vn/working/cuuam.vn/activation/register/order';

    function __construct() {
    }
    
    public function set_redirect_url($url) {
    	$this->redirect_uri = $url;
    }

    public function authorize($state = '', $redirect_uri = NULL) {
        $url  = 'https://id.gosu.vn/auth/authorize?response_type=code';
        $url .= '&client_id='    . $this->client_id;
        $url .= '&redirect_uri=' . (isset($redirect_uri) ? $redirect_uri : $this->redirect_uri);
        if (!empty($state)) {
            $url .= '&state=' . $state;
        }
        
        //echo $state; exit;
        return $url;
    }

    public function logout_link($url) {
        return 'https://id.gosu.vn/auth/auth/logout?returnURL=' . $url;
    }

    public function token($code, $redirect_url = NULL) {
        $url = 'https://id.gosu.vn/auth/token';
        
        $data = array(
            'grant_type'	=> 'authorization_code',
            'client_id' 	=> $this->client_id,
            'client_secret' => $this->client_secret,
            'redirect_uri'  => (isset($redirect_url) ? $redirect_url : $this->redirect_uri),
            'code'  		=> $code
        );       
        
        $token = $this->do_post_request($url, $data);        
        return json_decode($token, true);
    }

    private function do_post_request($url, $data=NULL) {        
        $ch = curl_init(); // Init cURL

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        if($data!=NULL){
        	curl_setopt($ch, CURLOPT_POST, 1);
        	$query = http_build_query($data);
        	curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        }
        
        $response = curl_exec($ch); // Execute the request
        curl_close($ch); // Finish the request

        if ($response) {
            return $response;
        } else {
            return NULL;
        }
    }

    public function get_user_info($access_token) {
    	$url = 'https://id.gosu.vn/auth/profile?access_token=' . $access_token;
        $content = $this->do_post_request($url);
        $result = json_decode($content);
        return $result;
    }
    
}